package org.snusmumr.android.media.data.adapter;

import java.util.ArrayList;
import java.util.List;

import org.snusmumr.android.media.R;
import org.snusmumr.android.media.bean.LabelModel;

import android.content.Context;
import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;

public class CheckedLabelCursorAdapter extends LabelCursorAdapter {
	private List<Integer> selected;

	public CheckedLabelCursorAdapter(Context context, Cursor c) {
		super(context, R.layout.select_label_dlg_field, c);
		this.selected = new ArrayList<Integer>();
	}
	
	@Override
	public View newView(Context context, Cursor cursor, ViewGroup parent) {
		LayoutInflater li = LayoutInflater.from(context);
        return li.inflate(R.layout.select_label_dlg_field, parent, false);
	}
	
	@Override
	public void bindView(View view, Context context, Cursor c) {
		super.bindView(view, context, c);
		int position = c.getPosition();
		CheckBox check = (CheckBox) view.findViewById(R.id.lb_check_label);
		check.setOnCheckedChangeListener(new CheckListener(position, selected));
		boolean selectedValue = selected.contains(position);
		check.setChecked(selectedValue);
	}
	
	public List<LabelModel> getSelectedLabels() {
		List<LabelModel> list = new ArrayList<LabelModel>(selected.size());
		if(selected.size() > 0) {
			Cursor c = getCursor();
			c.moveToFirst();
			do {
				int position = c.getPosition();
				if(selected.contains(position)) {
					list.add(getLabelModelFromCursor(c));
				}
			} while (c.moveToNext());
		}
		return list;
	}
	
	
	private LabelModel getLabelModelFromCursor(Cursor c) {
		return new LabelModel(c.getLong(0), c.getString(1), c.getInt(2));
	}
	
}
